import React, { Component } from "react";
import './Content.css'

export default class Content extends Component {
    state = {
        comments: [
            { id: 1, name: 'jack', content: '沙发！！！' },
            { id: 2, name: 'rose', content: '板凳~' },
            { id: 3, name: 'tom', content: '楼主好人' }
        ],
        name: "",
        context: ""
    }

    inputChange = (e) => {
        this.setState({
            name: e.target.value
        })
    }

    contextChange = (e) => {
        this.setState({
            context: e.target.value
        })
    }

    addComment = () => {
        let { name, context, comments } = this.state
        if (!name.trim() || !context.trim()) return alert("请先输入评论和评论人")
        let id = comments[comments.length - 1].id + 1
        this.setState({
            comments: [...comments, { id, name, content: context }]
        })
    }


    render() {
        let { name, context, comments } = this.state
        return (
            <div>
                <div className="box">
                    <h1>content 组件</h1>
                    <input type="text" placeholder="发表人" className="user" value={name} onChange={this.inputChange} />
                    <div>
                        <textarea name="" id="" cols="30" rows="10" value={context} onChange={this.contextChange}></textarea>
                        <br />
                        <button onClick={this.addComment}>发表评论</button>
                    </div>

                    {/* 内容展示 */}
                    <ShowComments data={comments}></ShowComments>

                </div>
            </div>
        )
    }
}


class ShowComments extends Component {

    render() {
        if (this.props.data.length === 0) {
            return <div className="no-comment" >暂无评论，快去评论吧~</div>
        } else {
            return (
                <ul>
                    {this.props.data.map((item) => {
                        return <li key={item.id}>{item.id} ----- {item.content} ----  {item.name}</li>
                    })}
                </ul>
            )

        }
    }
}